//
//  YKAlertView.m
//  YKAlert
//
//  Created by edward on 2020/8/21.
//  Copyright © 2020 edward. All rights reserved.
//

#import "YKAlertView.h"
#import <pthread.h>
#import <objc/message.h>

#define iPhoneX \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})

#define KSTATUSBAR_HEIGHT [UIApplication sharedApplication].statusBarFrame.size.height
#define screenW UIScreen.mainScreen.bounds.size.width
#define screenH UIScreen.mainScreen.bounds.size.height
#define speed 0.3

@implementation YKAlertView



#pragma mark -触发显示顶部VIew  我们将默认添加到当前控制器上去

+ (void)showView:(nonnull UIView *)view showType:(YKAlertShowType)showType bgAutoDissMiss:(BOOL)bgAutoDissMiss
{
    if (!view) {
        return;
    }
    CGFloat cgx,cgy,w,h;
    NSInteger tag;
    UISwipeGestureRecognizer *swip;
    if(showType == YKAlertShowTypeFromBottom || showType == YKAlertShowTypeFromBottom_withNullBac)
    {
        cgx = 15;
        cgy = screenH;
        w = screenW-30;
        h = view.bounds.size.height + 20;//100;
        swip = [[UISwipeGestureRecognizer alloc]init];
        swip.direction = UISwipeGestureRecognizerDirectionDown;
        tag = [YKAlertView k_AlertView_Bottom_Tag];
    }else if (showType == YKAlertShowTypeFromTop || showType == YKAlertShowTypeFromTop_withNullBac)
    {
        cgx = 15;
        cgy = 0 - view.bounds.size.height - 20;
        w = screenW-30;
        h = view.bounds.size.height + 20;//100;
        swip = [[UISwipeGestureRecognizer alloc]init];
        swip.direction = UISwipeGestureRecognizerDirectionUp;
        tag = [YKAlertView k_AlertView_Top_Tag];
    }else if (showType == YKAlertShowTypeFromLeft || showType == YKAlertShowTypeFromLeft_withNullBac)
    {
        cgx = 0 - screenW;
        cgy = KSTATUSBAR_HEIGHT;
        w = view.bounds.size.width+10;
        if (w > screenW) {
            w = screenW;
        }
        h = screenH-(KSTATUSBAR_HEIGHT)-(iPhoneX ? 34 : 15);
        swip = [[UISwipeGestureRecognizer alloc]init];
        swip.direction = UISwipeGestureRecognizerDirectionLeft;
        tag = [YKAlertView k_AlertView_Left_Tag];
    }else
    {
        w = view.bounds.size.width + 10;
        h = view.bounds.size.height + 10;
        cgx = ([[UIScreen mainScreen]bounds].size.width - w)/2;
        cgy = ([[UIScreen mainScreen]bounds].size.height - h)/2;
        if (cgx < 0) {
            cgx = 0;
            w = screenW;
        }
        if (cgy<0) {
            cgy = 0;
            h = screenH;
        }
        tag = [YKAlertView k_AlertView_Mid_Tag];
    }
    UIView *mainView = [[UIView alloc]initWithFrame:CGRectMake(cgx, cgy, w, h)];
    if (@available(iOS 13.0, *)) {
        mainView.backgroundColor = UIColor.systemBackgroundColor;
    } else {
        mainView.backgroundColor = UIColor.whiteColor;
    }
    // 阴影颜色
    mainView.layer.shadowColor = [UIColor.blackColor colorWithAlphaComponent:0.8].CGColor;
    // 阴影偏移，默认(0, -3)
    mainView.layer.shadowOffset = CGSizeMake(3, 3);
    // 阴影透明度，默认0
    mainView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    mainView.layer.shadowRadius = 5;
    mainView.userInteractionEnabled = YES;
    mainView.tag = tag + 1;
    mainView.layer.cornerRadius = (showType == YKAlertShowTypeFromLeft || showType == YKAlertShowTypeFromLeft_withNullBac)?0: 8;
    mainView.alpha = 1;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, screenH)];
    
    bgView.tag = tag;
    BOOL withNullbac = showType == YKAlertShowTypeFromTop_withNullBac || showType == YKAlertShowTypeFromBottom_withNullBac || showType == YKAlertShowTypeFromLeft_withNullBac || showType == YKAlertShowTypeMid_withNullBac;
    bgView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:withNullbac?0:0.8];
    if (bgAutoDissMiss) {
        //点击蒙版取消
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
        [tap addTarget:self action:@selector(dissShowGestureRecognizer:)];
        bgView.gestureRecognizers = nil;
        [bgView addGestureRecognizer:tap];
    }
    [bgView addSubview:mainView];
    if(view)
    {
        [mainView addSubview:view];
        if(showType == YKAlertShowTypeFromBottom || showType == YKAlertShowTypeFromBottom_withNullBac)
        {
            view.frame = CGRectMake((mainView.frame.size.width - view.bounds.size.width)/2, (mainView.frame.size.height - view.bounds.size.height)/2, view.bounds.size.width, view.bounds.size.height);
        }else if (showType == YKAlertShowTypeFromTop || showType == YKAlertShowTypeFromTop_withNullBac)
        {
            view.frame = CGRectMake((mainView.frame.size.width - view.bounds.size.width)/2, (mainView.frame.size.height - view.bounds.size.height)/2, view.bounds.size.width, view.bounds.size.height);
        }else if (showType == YKAlertShowTypeFromLeft || showType == YKAlertShowTypeFromLeft_withNullBac)
        {
            view.frame = CGRectMake(5, 5, view.frame.size.width, view.frame.size.height);
        }else
        {
            view.frame = CGRectMake((mainView.frame.size.width - view.bounds.size.width)/2, (mainView.frame.size.height - view.bounds.size.height)/2, view.bounds.size.width, view.bounds.size.height);
        }
    }
    
    UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    UIViewController *vc = window.rootViewController;
    while(vc.presentedViewController){vc=vc.presentedViewController;}
    [vc.view addSubview:bgView];
    CGFloat secx;
    CGFloat secy;
    if(showType == YKAlertShowTypeFromBottom || showType == YKAlertShowTypeFromBottom_withNullBac)
    {
        secx = 15;
        secy = UIScreen.mainScreen.bounds.size.height - CGRectGetHeight(mainView.frame) - (iPhoneX ? 34 : 15);
        [UIView animateWithDuration:speed animations:^{
            mainView.frame = CGRectMake(secx,
                                                secy,
                                                CGRectGetWidth(mainView.frame),
                                                CGRectGetHeight(mainView.frame));
        }];

    }else if (showType == YKAlertShowTypeFromTop || showType == YKAlertShowTypeFromTop_withNullBac)
    {
        secx = 15;
        secy = KSTATUSBAR_HEIGHT;
        [UIView animateWithDuration:speed animations:^{
            mainView.frame = CGRectMake(secx,
                                                secy,
                                                CGRectGetWidth(mainView.frame),
                                                CGRectGetHeight(mainView.frame));
        }];
    }
    else if (showType == YKAlertShowTypeFromLeft || showType == YKAlertShowTypeFromLeft_withNullBac)
    {
        secx = 0;
        secy = KSTATUSBAR_HEIGHT;
        [UIView animateWithDuration:speed animations:^{
            mainView.frame = CGRectMake(secx,
                                                secy,
                                                CGRectGetWidth(mainView.frame),
                                                CGRectGetHeight(mainView.frame));
        }];
    }else
    {
        mainView.center = CGPointMake(screenW/2, screenH/2);
        CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animation];
        bounceAnimation.duration = speed;
        bounceAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        bounceAnimation.values = [NSArray arrayWithObjects:
                                  [NSNumber numberWithFloat:0.8],
                                  [NSNumber numberWithFloat:1.05],
                                  [NSNumber numberWithFloat:0.98],
                                  [NSNumber numberWithFloat:1.0],
                                  nil];
        
        [mainView.layer addAnimation:bounceAnimation forKey:@"transform.scale"];
    }
    if(swip)
    {
        //滑动消失
        [swip addTarget:self action:@selector(dissShowGestureRecognizer:)];
        [mainView addGestureRecognizer:swip];
    }
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc]init];
    [singleTap addTarget:self action:@selector(doNothing)];//添加一个空的点击触发事件，一不影响手势滑动的事件，二是阻碍父控件的点击事件传递进来
    [mainView addGestureRecognizer:singleTap];
}

#pragma mark -取消显示
+ (void)dissView {
    if (pthread_main_np()) {
        [YKAlertView dissViewOnMainThread];
    } else {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [YKAlertView dissViewOnMainThread];
        });
    }
}

+ (void)dissViewOnMainThread
{
    UIView *view_top = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Top_Tag]];
    UIView *view_bottom = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Bottom_Tag]];
    UIView *view_Left = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Left_Tag]];
    UIView *view_Mid = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Mid_Tag]];
    CGFloat cgx,cgy;
    if(view_top)
            {
                cgx = 15;
        cgy = 0 - screenH;
        UIView *view_main = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Top_Tag]+1];
        [UIView animateWithDuration:speed animations:^{
            view_main.frame = CGRectMake(cgx,
                                                cgy,
                                                CGRectGetWidth(view_main.frame),
                                                CGRectGetHeight(view_main.frame));
        } completion:^(BOOL finished) {
            if(finished){[view_top removeFromSuperview];}
        }];
    }else if(view_bottom)
    {
        cgx = 15;
        cgy = screenH;
        UIView *view_bottom_main = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Bottom_Tag]+1];
        [UIView animateWithDuration:speed animations:^{
            view_bottom_main.frame = CGRectMake(cgx,
                                                cgy,
                                                CGRectGetWidth(view_bottom_main.frame),
                                                CGRectGetHeight(view_bottom_main.frame));
        } completion:^(BOOL finished) {
            if(finished){[view_bottom removeFromSuperview];}
        }];
    }else if(view_Left)
    {
        cgx = 0 - screenW;
        cgy = KSTATUSBAR_HEIGHT;
        UIView *view_main = [[UIApplication sharedApplication].keyWindow viewWithTag:[YKAlertView k_AlertView_Left_Tag]+1];
        [UIView animateWithDuration:speed animations:^{
            view_main.frame = CGRectMake(cgx,
                                                cgy,
                                                CGRectGetWidth(view_main.frame),
                                                CGRectGetHeight(view_main.frame));
        } completion:^(BOOL finished) {
            if(finished){[view_Left removeFromSuperview];}
        }];
    }else if (view_Mid){[view_Mid removeFromSuperview];}
    
    
}


#pragma mark 默认取消动作
+ (void)dissShowGestureRecognizer:(id)sender
{
    void (^callBack)(void) = ((NSDictionary *)objc_getAssociatedObject(sender, @"myBtn"))[@"block"];
    [YKAlertView dissView];
    if (callBack) {
        callBack();
    }
}

+ (void)doNothing
{
    
}

#pragma mark -------标记-------
+ (NSInteger)k_AlertView_Top_Tag
{
    return 865;
}
+ (NSInteger)k_AlertView_Bottom_Tag
{
    return 867;
}
+ (NSInteger)k_AlertView_Left_Tag
{
    return 869;
}
+ (NSInteger)k_AlertView_Mid_Tag
{
    return 871;
}

@end
